const qiniu = require('qiniu')
const formidable = require('formidable')
const { bucket, url, accessKey, secretKey } =  require('./config')

const qn = {};

// 构建上传策略函数 （获取七牛云上传token）
qn.uptoken = function(bucket) {
    let putPolicy = new qiniu.rs.PutPolicy({ scope: bucket })
    let mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
    let uploadToken = putPolicy.uploadToken(mac)
    return uploadToken
}

qn.upImg = function(files){
    let callbackObj = {} // 回调函数返回的对象

    // 后缀名
    let hz = files.file.name.substring(files.file.name.indexOf('.'), files.file.name.length)
    let key = `${new Date().getTime()}${Math.floor((Math.random() * 1000) + 1)}${hz}`;
    //生成上传 Token
    let token = qn.uptoken(bucket);
    //要上传文件的本地路径
    let filePath = files.file.path;

    //构造上传函数
    // 文件上传（以下四行代码都是七牛上传文件的配置设置）
    var config = new qiniu.conf.Config();
    config.zone = qiniu.zone.Zone_z2;  //设置传输机房的位置根据自己的设置选择
    var formUploader = new qiniu.form_up.FormUploader(config);
    var putExtra = new qiniu.form_up.PutExtra();
    return new Promise((resolve, reject) => {
        formUploader.putFile(token, key, filePath, putExtra, function (respErr, respBody, respInfo) {
            if (respErr) {
                callbackObj.status = 1;
                callbackObj.msg = respErr;
                resolve(callbackObj) ;
            }
            if (respInfo.statusCode == 200) {//上传成功
                // 输出 JSON 格式  xxx填写自己在七牛中设置的自定义域名
                var response = {
                    "url": url + key
                };
                console.log(response);
                // res.end(JSON.stringify(response));
                callbackObj.status = 0;
                callbackObj.data = response;
                resolve(callbackObj)
            } else {//上传失败
                console.log(respInfo.statusCode);
                console.log(respBody);
                callbackObj.status = 1;
                callbackObj.msg = respBody;
                reject(callbackObj)
            }
        });
    }) 
}

module.exports = qn